#!/usr/bin/env python

import inkex, simplepath
import simpleclass
from lxml import etree
from OrigamiHelper import molecules
from OrigamiHelper import stylist

class Molecule(inkex.Effect):
    """Create the selected molecules"""
    def __init__(self):
        """ main stream"""
        inkex.Effect.__init__(self)
        self.OptionParser.add_option("-m", "--molecule",
                        action="store", type="string",
                        dest="molecule", default="",
                        help="Molecule type")
        self.OptionParser.add_option("-l", "--length",
                        action="store", type="float",
                        dest="length", default="0.5",
                        help="Length of blablalba")
        self.OptionParser.add_option("-p", "--point",
                        action="store", type="int",
                        dest="point", default="1",
                        help="Point")
    def effect(self) :
        """Select the chosen molecule"""
        #TODO create a group
        #TODO put the path inside it
        for id, node in self.selected.iteritems():
            d = node.get("d")
            points = simplepath.parsePath(d)
            m = molecules.Molecules(points)
            if self.options.molecule[1:2] == "r" :
                self.pathList = m.rabbitEar()
            elif self.options.molecule[1:2] == "w" :
                self.pathList = m.waterbomb()
            elif self.options.molecule[1:2] == "a" :
                self.pathList = m.arrowhead(self.options.point-1,self.options.length)
            elif self.options.molecule[1:2] == "g" :           
                self.pathList = m.gusset(self.options.point-1,self.options.length)            
            else :
                raise Exception, "no molecule chosen: %s" % self.options.molecule
            self.createCP(node)
    
    def createCP(self,node) :
        new = self.current_layer
        i = 0
        while i < len(self.pathList) :
            object = etree.SubElement(node.getparent(), inkex.addNS('path','svg'))
            path = [["M", [self.pathList[i][0][0]['x'], self.pathList[i][0][0]['y']]], 
                    ["L", [self.pathList[i][0][1]['x'], self.pathList[i][0][1]['y']]] ]
            object.set('d', simplepath.formatPath(path))
            # set the styles
            #TODO choice the pattern 
            style = ["mark","mountain_fold","valley_fold"]
            object.attrib["class"] =  simpleclass.format(stylist.classes[(style[self.pathList[i][1]])])
            i += 1
        
# Create effect instance and apply it.
Effect = Molecule()
Effect.affect()